﻿using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Quickly.Certs.EntityFrameworkCore
{
    public abstract class AbstractCertsContextPostgresFactory : IDesignTimeDbContextFactory<CertsContext>
    {
        public abstract string Database { get; }

        public CertsContext CreateDbContext(string[] args)
        {
            var serviceProvider = BuildDesignTimeServiceProvider(args, Database);

            return serviceProvider.GetRequiredService<CertsContext>();
        }

        protected virtual IServiceProvider BuildDesignTimeServiceProvider(string[] args, string databaseType)
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder
                .AddCommandLine(args)
                .AddEnvironmentVariables()
                .AddJsonFile("appsettings.json", optional: true);

            var configuration = configurationBuilder.Build();

            var services = new ServiceCollection();
            services.AddScoped<IConfiguration>(sp => configuration);
            services.Configure<DatabaseOption>(option => option.Type = databaseType);
            services.AddDbContext<CertsContext>(EntityFrameworkCoreBuilderExtensions.BuildConfigureDatabase("Default"));

            var serviceProvider = services.BuildServiceProvider();

            return serviceProvider;
        }
    }
}
